import express from "express";
import { PrismaClient } from "@prisma/client";
const app = express();
const prisma = new PrismaClient();
const prot = 5000;
app.use(express.json());

// 创建用户
app.post("/createUser", async (req, res) => {
  const { name, email } = req.body;
  const data = await prisma.user.create({
    data: {
      name,
      email,
      posts: {
        create: [
          {
            title: "文章1",
            publish: true,
          },
          {
            title: "文章2",
            publish: false,
          },
        ],
      },
    },
  });
  res.send(data);
});

// 查询所有用户
app.get("/users", async (req, res) => {
  const data = await prisma.user.findMany({
    // 包含关联数据
    include: {
      posts: true,
    },
  });
  res.send(data);
});

// 查询某个用户
app.get("/user/:id", async (req, res) => {
  const { id } = req.params;
  const data = await prisma.user.findUnique({
    where: {
      id: parseInt(id),
    },
    include: {
      posts: true,
    },
  });
  res.send(data);
});

// 更新用户
app.put("/user/:id", async (req, res) => {
  const { id } = req.params;
  const { name, email } = req.body;
  const data = await prisma.user.update({
    where: {
      id: parseInt(id),
    },
    data: {
      name,
      email,
    },
  });
  res.send(data);
});

// 删除用户
app.delete("/user/:id", async (req, res) => {
  const { id } = req.params;

  // 删除用户之前需要先删除用户的文章
  await prisma.post.deleteMany({
    where: {
      authorId: parseInt(id),
    },
  });

  const data = await prisma.user.delete({
    where: {
      id: parseInt(id),
    },
  });
  res.send(data);
});

// 查询用户总数
app.get("/userCount", async (req, res) => {
  const data = await prisma.user.count();
  res.send({
    count: data,
  });
});

app.listen(prot, () => {
  console.log(`Server is running on port ${prot}`);
});
